package com.atguigu.krp.handler;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author KEIO  on 2022/1/14.
 * @version 1.0
 */
@Slf4j
@Component
public class ServerBootStrapHelper {

    public synchronized void bootStart(EventLoopGroup bossGroup, EventLoopGroup workerGroup,
                                       String host, int serverPort, ChannelInitializer channelInitializer) throws Exception {
        /*
        启动监听
         */
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(channelInitializer)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            //连接超时时间，连接公网服务器时可能会超时导致连接失败，最好不要设置
            //.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,10000);
            // 进行同步端口绑定
            Channel channel = serverBootstrap.bind(host, serverPort).sync().channel();

            // 指定的是  lambda表达式  实现的接口类型  ChannelFutureListener没有抽象方法  本质是几成自 其父亲接口
            channel.closeFuture().addListener((ChannelFutureListener) future -> {
                channel.deregister();
                channel.close();
            });
        } catch (InterruptedException e) {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            log.info("bootStart中出现异常  启动终止");
            e.printStackTrace();
        }


    }


}
